<template>
  <div>
    <!-- 正式客户 -->
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="csmRgPhone" label="电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="externalCsmCode" label="外部客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmRgAddress" label="地址" />
          <!-- <el-option value="salesmanName" label="销售人员" />
          <el-option value="remark" label="备注" />
          <el-option value="auditor" label="审核人" /> -->
          <el-option value="sfzh" label="身份证号" />
          <el-option value="cardNoBus" label="营业执照编码" />
          <el-option value="licenseUserName" label="法人代表" />
          <el-option value="csmRgAddress" label="地址" />
          <el-option value="groupCode" label="客户组号" />
          <el-option value="openAccountPhone" label="开户电话" />
          <!-- <el-option value="cardType1" label="使用证" />
          <el-option value="cardType2" label="充值卡" />
          <el-option value="countryName" label="区" />
          <el-option value="streetName" label="街道" /> -->
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="开户日期" value="createTime" />
          <!-- <el-option label="销户日期" value="cancelTime" /> -->
          <el-option label="最后订气时间" value="lastBuyDt" />
          <el-option label="主体变更时间" value="subjectModifyTime" />
          <!-- <el-option label="一户一码绑定时间" value="bindTime" /> -->
        </el-select>
        <el-date-picker
          v-model="date"
          clearable
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="clearTree"
        />
      </el-form-item>
      <el-form-item label="客户类型:" prop="csmType">
        <el-select v-model="query.csmType" clearable placeholder="请选择" @change="csmTypeChange">
          <el-option
            v-for="(item,index) in customerTypeMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用气性质:" prop="subType">
        <el-select v-model="query.subType" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in subTypeList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类别:" prop="csmType">
        <el-select v-model="query.gasNature" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in cardTypeAllList"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="隐患等级:" prop="warnLevel">
        <el-select v-model="query.warnLevel" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in warnLevelMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="csmStatus">
        <el-select v-model="query.csmStatus" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in csmStatusMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源:" prop="newFrom">
        <el-select v-model="query.newFrom" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in newFromMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否自提:" prop="isPickUp">
        <el-select v-model="query.isPickUp" clearable placeholder="请选择">
          <el-option :value="1" label="是" />
          <el-option :value="-1" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="结款方式:" prop="settlementType">
        <el-select v-model="query.settlementType" clearable placeholder="请选择">
          <el-option :value="1" label="现结" />
          <el-option :value="2" label="月结" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序:" prop="orderBy">
        <el-select v-model="query.orderBy" clearable placeholder="请选择">
          <el-option :value="1" label="按开户日期" />
          <el-option :value="2" label="按积分余额" />
          <el-option :value="3" label="按历史总积分" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="客户等级:" prop="unCheckQuality">
        <el-select v-model="query.unCheckQuality" clearable placeholder="请选择">
          <el-option
            v-for="item in csmLevelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="活跃度:" prop="labelSource">
        <el-select v-model="query.labelSource" multiple clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in labelMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主体变更:" prop="isSubjectChange">
        <el-select v-model="query.isSubjectChange" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in [{desc:'是',value:1}]"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="一户一码:" prop="bindStatus">
        <el-select v-model="query.bindStatus" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in bindStatusMap"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="安装人:" prop="bindStatus">
        <el-select v-model="query.bindUserId" filterable clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in ownersList"
            :key="index"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="安装人:" prop="bindUserName">
        <el-input v-model="bindUserName" readonly>
          <el-button v-if="!bindUserName" slot="append" class="append-search" @click="openBindUser">获取</el-button>
          <el-button v-else slot="append" class="append-search" @click.prevent="clearBindUser">清除</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="销售人员:" prop="salesmanName">
        <el-input v-model="salesmanName" readonly>
          <el-button v-if="!salesmanName" slot="append" class="append-search" @click="openSalesman">获取</el-button>
          <el-button v-else slot="append" class="append-search" @click.prevent="clearSalesman">清除</el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="区/县:" prop="countryCode">
        <el-select v-model="query.countryCode" clearable placeholder="请选择" @change="getStreetlist">
          <el-option
            v-for="(item,index) in areaData"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="街道:" prop="streetCode">
        <el-select v-model="query.streetCode" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in streetlist"
            :key="index"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button v-permission="[20101,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="[20101,2]" type="primary" icon="el-icon-circle-plus-outline" @click="addCsm">新增</el-button>
        <!-- <el-button type="primary" icon="el-icon-s-check" @click="batchAudit">批量审核</el-button> -->
        <el-button v-permission="[20101,3]" type="primary" icon="el-icon-edit" @click="onUpdateAllOrg">批量修改</el-button>
        <el-button v-permission="[20101,4]" type="primary" icon="el-icon-download" @click="exportFile(0)">导出</el-button>
        <el-button v-permission="[20101,5]" type="primary" icon="el-icon-download" @click="exportFile(1)">非脱敏导出</el-button>
        <!-- <el-button v-permission="11" type="primary" @click="onUpdateAll">批量编辑 </el-button> -->
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @selection-change="selectionChange"
      @current-change="handleCurrentChange"
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" :group-type-map="groupTypeMap" />
    <add-csm ref="addCsm" :parent-fetch-data="refresh" :tree-data="treeData" :group-type-map="groupTypeMap" />
    <edit-csm ref="editCsm" :parent-fetch-data="refresh" :tree-data="treeData" :group-type-map="groupTypeMap" />
    <update-code ref="updateCode" :parent-fetch-data="refresh" />
    <customerAudit ref="customerAudit" :parent-fetch-data="refresh" :tree-data="treeData" />
    <insure ref="insure" />
    <normalReceiptsAdd ref="normalReceiptsAdd" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <refillCard ref="refillCard" :card-status-map="accCsmcardCardStatusMap" />
    <occupy ref="occupy" />
    <customerLocation ref="customerLocation" />
    <xiaohu ref="xiaohu" :xiao-hu-fn="xiaoHuFn" />
    <exportDiglog ref="export" />
    <up-data-all ref="upDataAll" :tree-data="treeData" @upDataTable="upDataTable" />
    <warnInfo ref="warnInfo" />
    <salesman ref="salesman" :tree-data="treeData" />
    <csmGroupDetail ref="csmGroupDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" :csm-status-map="csmStatusMap" :group-type-map="groupTypeMap" :csm-type-map="customerTypeMap" :sub-type-all-list="subTypeAllList" />
    <updateOrg ref="updateOrg" :tree-data="treeData" />
    <blacklistCsm ref="blacklistCsm" />
  </div>
</template>

<script>
  import { formatColumnMap, isWildPhone, parseTime } from '@/utils'
  import moment from 'dayjs'
  import { csmManageQueryList, querySubTypeMap, queryOwnersList, queryAddCsmDefaultData, customerInfo, customerInvocie, customerCancle, customerLocation, updateCsmStatus, csmCancelPrint, getCustomerLabel, cancelCsmGroup, selectAreaCode } from '@/api'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import AddCsm from './AddCsm'
  import EditCsm from './EditCsm'
  import UpdateCode from './UpdateCode'
  import CustomerAudit from './CustomerAudit'
  import Insure from './Insure'
  import NormalReceiptsAdd from '@/views/components/NormalReceiptsAdd'
  import RefillCard from './RefillCard'
  import Occupy from './Occupy'
  import CustomerLocation from './CustomerLocation'
  import warnInfo from './WarnInfo.vue'
  import { mapGetters } from 'vuex'
  import { minDate } from '@/utils/config'
  import xiaohu from './xiaohu'
  import Salesman from './Salesman'
  import UpDataAll from './UpDataAll.vue'
  import csmGroupDetail from './csmGroupDetail.vue'
  import updateOrg from './updateOrg'
  import blacklistCsm from './blacklistCsm.vue'

  export default {
    name: 'real-csm-tab',
    components: {
      CsmDetail, AddCsm, EditCsm, CustomerAudit, Insure, NormalReceiptsAdd, RefillCard, Occupy, CustomerLocation, xiaohu, UpDataAll, UpdateCode, warnInfo, Salesman,
      exportDiglog: require('./export.vue').default,
      csmGroupDetail,
      updateOrg,
      blacklistCsm
    },
    props: {
      csmLerel: {
        type: Number,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      customerTypeMap: {
        type: Array,
        required: true
      },
      subTypeAllList: {
        type: Array,
        required: true
      },
      newFromMap: {
        type: Array,
        required: true
      },
      csmStatus: {
        type: Array,
        required: true
      },
      csmLevelMap: {
        type: Array,
        required: true
      },
      csmNewTypeMap: {
        type: Array,
        required: true
      },
      accCsmcardCardStatusMap: {
        type: Array,
        required: true
      },
      calcTypeList: {
        type: Array,
        required: true
      },
      paymenFilList: {
        type: Array,
        required: true
      },
      warnLevelMap: {
        type: Array,
        require: true
      },
      groupTypeMap: {
        type: Array,
        require: true
      }
    },
    data() {
      return {
        qtype: 'csmRgPhone',
        dateType: 'createTime',
        txt: '',
        date: [],
        updateList: [], // 批量操作
        ids: [],
        subTypeList: [],
        labelMap: [
          { desc: '月度活跃', value: 4 },
          { desc: '季度活跃', value: 5 },
          { desc: '半年活跃', value: 6 },
          { desc: '沉睡', value: 2 },
          { desc: '休眠', value: 3 }
        ],
        bindStatusMap: [{ desc: '未绑定', value: 1 }, { desc: '已绑定', value: 2 }],
        cardTypeAllList: [], // 客户类别枚举
        ownersList: [], // 安装人
        actionColWidth: 80,
        invalidStr: '',
        salesmanName: '',
        bindUserName: '',
        query: {
          csmType: '',
          csmStatus: '',
          newFrom: '',
          isPickUp: '',
          settlementType: '',
          orderBy: 1,
          unCheckQuality: '',
          subType: '',
          bindStatus: null,
          isSubjectChange: null,
          bindUserId: null,
          salesman: '',
          countryCode: '',
          streetCode: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        orgId: '',
        areaData: [],
        streetlist: []
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'corpSettingData'
      ]),
      csmStatusMap: function() {
        return this.csmStatus.filter(item => item.value !== -1)
      },
      column: function() {
        const cols = [
          {
            type: 'index',
            fixed: 'left'
          },
          {
            type: 'selection',
            fixed: 'left'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 105,
            fixed: 'left',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'isShare',
            label: '共享',
            formatter: row => {
              return row.isShare === 0 ? '非共享' : row.isShare === 1 ? '共享' : ''
            }
          },
          {
            prop: 'label',
            label: '活跃度',
            render: (h, { row }) => <span>{ row.label && formatColumnMap(this.labelMap, 'value', row.label, 'desc') }</span>
          },
          {
            prop: 'bindStatus',
            label: '一户一码',
            render: (h, { row }) => <span>{ row.bindStatus && formatColumnMap(this.bindStatusMap, 'value', row.bindStatus, 'desc') }</span>
          },
          {
            prop: 'bindTime',
            label: '一户一码绑定时间',
            width: 160,
            render: (h, { row }) => <span>{ row.bindTime && parseTime(row.bindTime, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
          },
          {
            prop: 'openAccountPhone',
            width: 110,
            label: '开户电话'
          },
          {
            prop: 'bindUser',
            label: '安装人'
            // render: (h, { row }) => <span>{ row.bindStatus && formatColumnMap(this.bindStatusMap, 'value', row.bindStatus, 'desc') }</span>
          },
          {
            prop: 'bindCount',
            label: '变更次数'
            // render: (h, { row }) => <span>{ row.bindStatus && formatColumnMap(this.bindStatusMap, 'value', row.bindStatus, 'desc') }</span>
          },
          {
            prop: 'openId',
            align: 'center',
            label: '微信用户',
            render: (h, { row }) => row.openId && <svg-icon icon-class='wechat-icon' />
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'subType',
            label: '用气性质',
            width: 110,
            render: (h, { row }) => <span>{ row.subType ? formatColumnMap(this.subTypeAllList, 'value', row.subType, 'label') : ''}</span>
          },
          // {
          //   prop: 'csmQuality',
          //   label: '客户等级',
          //   render: (h, { row }) => {
          //     if (this.csmLerel === 1) return <span>{ row.csmQuality ? formatColumnMap(this.csmLevelMap, 'value', row.csmQuality, 'desc') : '' }</span>
          //     else {
          //       if (row.qualityStatus === 2) {
          //         return <span>{ row.unCheckQuality ? formatColumnMap(this.csmLevelMap, 'value', row.unCheckQuality, 'desc') : '' }</span>
          //       } else {
          //         return <span style='color: red;'>{ row.unCheckQuality ? formatColumnMap(this.csmLevelMap, 'value', row.unCheckQuality, 'desc') : '' }</span>
          //       }
          //     }
          //   }
          // },
          {
            prop: 'csmRgPhone',
            width: 110,
            label: '联系电话'
          },
          {
            prop: 'newType',
            label: '气瓶使用方式',
            render: (h, { row }) => <span>{ row.newType ? formatColumnMap(this.csmNewTypeMap, 'value', row.newType, 'desc') : '租用瓶' }</span>
          },
          {
            prop: 'newFrom',
            width: 150,
            label: '客户来源',
            render: (h, { row }) => <span>{ row.newFrom && formatColumnMap(this.newFromMap, 'value', row.newFrom, 'desc') }</span>
          },
          {
            prop: 'cardNoBus',
            width: 150,
            label: '营业执照号'
          },
          {
            prop: 'licenseName',
            width: 240,
            label: '营业执照名称'
          },
          {
            prop: 'licenseUserName',
            width: 80,
            label: '法人代表'
          },
          {
            prop: 'deposit',
            width: 100,
            align: 'right',
            label: '押金'
          },
          {
            prop: 'csmRgAddress',
            width: 200,
            label: '地址',
            render: (h, { row }) => <span >
              <span class='point-span' onClick={() => this.getMap(row)}>{this.$permission(8) && <i class='el-icon-location linkColor' style='cursor: pointer;'/>}</span>{ row.csmRgAddress }
            </span>
          },
          {
            prop: 'doorplate',
            width: 100,
            label: '门牌号'
          },
          {
            prop: 'nearStationName',
            width: 150,
            label: '所属机构'
          },
          {
            prop: 'groupCode',
            width: 110,
            label: '客户组号',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.opencsmGroupDetaill(row)}>{row.groupCode}</el-link>
          },
          {
            prop: 'groupName',
            label: '组名称'
          },
          {
            prop: 'cardCount',
            align: 'right',
            label: '充值卡',
            render: (h, { row }) => row.cardCount ? <el-link underline={false} style='margin-right: 0;' onClick={() => this.openRefillCard(row)}>{row.cardCount}</el-link> : <span>{row.cardCount}</span>
          },
          {
            prop: 'lastSCheckDt',
            width: 180,
            label: '最后安检时间',
            render: (h, { row }) => row.lastSCheckDt && (new Date(row.lastSCheckDt).getTime() >= new Date(minDate).getTime()) && <span>{ parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            label: '隐患等级',
            align: 'center',
            prop: 'warnLevel',
            render: (h, { row }) =>
              row.warnLevel ? (
              <el-link underline={false} onClick={() => this.warnInfo(row)}>
                {formatColumnMap(this.warnLevelMap, 'value', row.warnLevel, 'desc')}
              </el-link>
                ) : (
              <span>
                {formatColumnMap(this.warnLevelMap, 'value', row.warnLevel, 'desc')}
              </span>
            )
          },
          {
            prop: 'lastBuyDt',
            width: 180,
            label: '最后订气时间',
            render: (h, { row }) => row.lastBuyDt && (new Date(row.lastBuyDt).getTime() >= new Date(minDate).getTime()) && <span>{ parseTime(row.lastBuyDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'score',
            align: 'right',
            label: '积分'
          },
          {
            prop: 'totalGasCount',
            align: 'right',
            label: '使用瓶数'
          },
          {
            prop: 'isPickUp',
            label: '自提客户',
            render: (h, { row }) => <span>{ row.isPickUp === 1 ? '是' : '否' }</span>
          },
          {
            prop: 'settlementType',
            label: '结款方式',
            render: (h, { row }) => <span>{ row.settlementType === 1 ? '现结' : '月结' }</span>
          },
          {
            prop: 'csmStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.csmStatus && formatColumnMap(this.csmStatusMap, 'value', row.csmStatus, 'desc') }</span>
          },
          {
            prop: 'createTime',
            width: 110,
            label: '开户日期',
            render: (h, { row }) => <span>{ row.createTime && (new Date(row.createTime).getTime() >= new Date(minDate).getTime()) && parseTime(row.createTime, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'createUser',
            label: '开户人'
          },
          {
            prop: 'salesmanName',
            label: '销售人员'
          },
          {
            prop: 'cancelTime',
            width: 110,
            label: '销户日期',
            render: (h, { row }) => <span>{ row.cancelTime && (new Date(row.cancelTime).getTime() >= new Date(minDate).getTime()) && parseTime(row.cancelTime, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'cancelUser',
            label: '销户人'
          },
          {
            prop: 'invalidStr',
            label: '销户原因'
          },
          {
            prop: 'curGasCount',
            align: 'right',
            label: '占用瓶数',
            render: (h, { row }) => row.curGasCount ? <el-link underline={false} style='margin-right: 0;' onClick={() => this.openOccupy(row)}>{row.curGasCount}</el-link> : <span>{row.curGasCount}</span>
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'csmOption3',
            label: '售卖方式'
          },
          {
            prop: 'csmOption5',
            label: '安全合同'
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'sfzh',
            width: 200,
            label: '身份证号'
          },
          {
            prop: 'contractNumber',
            label: '合同号'
          },
          {
            prop: 'strSpare1',
            label: '使用权费'
          },
          {
            prop: 'subjectModifyTime',
            label: '主体变更',
            width: 110,
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.subjectModifyTime ? parseTime(row.subjectModifyTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''}</span>
          },
          {
            prop: 'externalCsmCode',
            label: '外部客户编号',
            width: 110
          },
          {
            prop: 'brakingRemark',
            label: '拉黑原因',
            showOverflowTooltip: true
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      <el-dropdown-item>
                        {(row.csmStatus !== -1 && row.csmStatus !== 2 && row.csmStatus !== 4) && (<el-link v-permission={[20101, 7]} underline={false} size='mini' onClick={() => this.update(row, 'audit')}>
                          审核
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {row.csmStatus !== -1 && (<el-link v-permission={[20101, 6]} underline={false} size='mini' onClick={() => this.update(row, 'edit')}>
                          编辑
                        </el-link>)}
                      </el-dropdown-item>

                      <el-dropdown-item>
                        {row.csmStatus !== -1 && (<el-link v-permission={[20101, 8]} underline={false} size='mini' onClick={() => this.insurance(row, $index)}>
                          投保
                        </el-link>)}
                      </el-dropdown-item>

                      <el-dropdown-item>
                        {row.csmStatus !== -1 && (<el-link v-permission={[20101, 9]} underline={false} size='mini' onClick={() => this.normalReceiptsAdd(row, $index)}>
                          押金登记
                        </el-link>)}
                      </el-dropdown-item>

                      <el-dropdown-item>
                        {row.csmStatus !== -1 && (<el-link v-permission={[20101, 10]} underline={false} size='mini' onClick={() => this.updateCode(row, $index)}>
                          编号变更
                        </el-link>)}
                      </el-dropdown-item>

                      <el-dropdown-item>
                        {(row.csmStatus !== 1 && row.csmStatus !== -1) && (<el-link v-permission={[20101, 11]} underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
                          销户
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {(row.csmStatus === 2) && (<el-link v-permission={[20101, 12]} underline={false} size='mini' type='danger' onClick={() => this.blacklistCsm(row, $index)}>
                          拉黑
                        </el-link>)}
                      </el-dropdown-item>

                      <el-dropdown-item>
                        {(row.csmStatus === 4) && (<el-link v-permission={[20101, 13]} underline={false} size='mini' onClick={() => this.updateCsmStatus(row, $index)}>
                          移除拉黑
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {row.groupCode && (<el-link v-permission={[20101, 15]} underline={false} size='mini' type='danger' onClick={() => this.removeGroup(row, $index)}>
                          移除组
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-link v-permission={[20101, 14]} underline={false} size='mini' onClick={() => this.tryPrint(row, $index)}>
                          打印
                        </el-link>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
        if (this.userInfo.corpCode !== '22016') {
          const csmOption3 = cols.findIndex(item => item.prop === 'csmOption3')
          cols.splice(csmOption3, 1)
          const csmOption5 = cols.findIndex(item => item.prop === 'csmOption5')
          cols.splice(csmOption5, 1)
        }
        return cols
      }
    },
    mounted() {
      Promise.all([this.getOwnersList(), this.getStatusMap(), this.getCustomerLabelData(), this.getAreaData()])
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        // 电话号码校验
        if (this.qtype === 'csmRgPhone' && this.txt) {
          if (!isWildPhone(this.txt)) {
            this.$message.error('请输入正确的电话号码!')
            return
          }
          // if (this.txt.length !== 11) {
          //   this.$message.error('请输入正确的电话号码!')
          //   return
          // }
        }
        if (this.qtype === 'cardType1') {
          query.cardType = 1
          query.cardNo = this.txt
          delete query.cardType1
        } else if (this.qtype === 'cardType2') {
          query.cardType = 2
          query.cardNo = this.txt
          delete query.cardType2
        }
        if (this.qtype !== 'cardType1' && this.qtype !== 'cardType2') {
          if (query.cardNo) delete query.cardNo
        }
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        let csmQuality = this.query.unCheckQuality
        if (this.customerLerel === 1) {
          query.csmQuality = csmQuality
        } else {
          if (!csmQuality) {
            csmQuality = 0
          }
          query.unCheckQuality = csmQuality
        }
        if (!this.query.csmStatus) query.csmStatus = 9
        if (query.warnLevel === 0) query.warnLevel = -1
        const res = await csmManageQueryList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      csmTypeChange(csmType) {
        this.query.subType = ''
        this.subTypeList = []
        this.getSubTypeMap(csmType)
      },
      async getSubTypeMap(csmType) {
        const res = await querySubTypeMap({ csmType })
        this.subTypeList = res.data
      },
      async getStatusMap() {
        const res = await queryAddCsmDefaultData()
        // this.statusMap = res.data.map(l => JSON.parse(l))
        var obj = {}
        for (var value in res.data) {
          // console.log(item)
          if (this.isJsonString(res.data[value])) {
            var item = JSON.parse(res.data[value])
            obj[value] = item
          }
        }
        this.cardTypeAllList = obj.cardTypeAllList
      },
      isJsonString(str) {
        try {
          if (typeof JSON.parse(str) === 'object') {
            return true
          }
        } catch (e) {
          console.log()
        }
        return false
      },
      // 活跃度
      async getCustomerLabelData() {
        const res = await getCustomerLabel()
        if (res && res.data) {
          this.labelMap = res.data
        }
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.bindUserId = null
        this.orgId = value.orgId
        this.getOwnersList(value.orgId)
      },
      // 清空所属机构
      clearTree(v) {
        this.orgId = ''
        this.query.bindUserId = null
        this.getOwnersList()
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId: org || '',
          corpparm1: b
        })
        this.ownersList = res.data
      },
      // 点击获取安装人
      async openBindUser() {
        const res = await this.$refs.salesman.open(this.orgId, 'bindUser')
        this.currentBindUser = res
        this.query.bindUserId = res.userId
        this.bindUserName = res.userName
      },
      // 清除安装人
      clearBindUser() {
        this.currentBindUser = null
        this.query.bindUserId = ''
        this.bindUserName = ''
      },
      // 点击获取销售员
      async openSalesman() {
        const res = await this.$refs.salesman.open(this.orgId, 'salesman')
        this.currentSalesman = res
        this.query.salesman = res.userId
        this.salesmanName = res.userName
      },
      // 清除销售员
      clearSalesman() {
        this.salesmanName = ''
        this.query.salesman = ''
        this.currentSalesman = null
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 新增
      async addCsm() {
        await this.$refs.addCsm.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 批量编辑
      onUpdateAll() {
        if (!this.updateList.length) {
          this.$message({
            message: '请勾选批量修改选项',
            type: 'warning'
          })
          return
        }
        this.$refs.upDataAll.open(this.updateList)
      },
      // 批量修改机构
      async onUpdateAllOrg() {
        if (!this.updateList.length) {
          this.$message({
            message: '请勾选批量修改选项',
            type: 'warning'
          })
          return
        }
        await this.$refs.updateOrg.open(this.updateList)
        this.search()
      },
      // 审核
      async customerAudit(row) {
        const code = {
          csmCode: row.csmCode
        }
        const res = await customerInfo(code)
        const csmId01 = {
          csmId: row.csmId,
          taxType: 1
        }
        const csmId02 = {
          csmId: row.csmId,
          taxType: 2
        }
        const res01 = await customerInvocie(csmId01)
        const res02 = await customerInvocie(csmId02)
        await this.$refs.customerAudit.open(res, res01, res02)
      },
      // 编辑
      async update(row, type) {
        const code = {
          csmCode: row.csmCode
        }
        const res = await customerInfo(code)
        const csmId01 = {
          csmId: row.csmId,
          taxType: 1
        }
        const csmId02 = {
          csmId: row.csmId,
          taxType: 2
        }
        var list = [res.data.provinceCode, res.data.cityCode, res.data.countryCode, res.data.streetCode].filter(l => l * 1 !== 0 && l !== undefined)

        res.data.AddressData = [...list]
        const res01 = await customerInvocie(csmId01)
        const res02 = await customerInvocie(csmId02)
        await this.$refs.editCsm.open(res, res01, res02, type)
        this.$refs.editCsm.$refs.clientInformation.cascaderKey++
      },
      // 编号变更
      async updateCode(row) {
        await this.$refs.updateCode.open(row)
      },
      // 投保
      async insurance(row) {
        await this.$refs.insure.open(row)
      },
      // 押金登记
      async normalReceiptsAdd(row) {
        const res = await customerInfo({ csmCode: row.csmCode })
        await this.$refs.normalReceiptsAdd.open(res.data, 'add', 'toubao', row)
      },
      // 充值卡
      async openRefillCard(row) {
        await this.$refs.refillCard.open(row)
      },
      // 占用瓶
      async openOccupy(row) {
        await this.$refs.occupy.open(row)
      },
      // 勾选事件
      selectionChange(val) {
        this.updateList = val
      },
      // 获取选中
      handleCurrentChange(val) {
        this.ids = val
      },
      // 客户位置
      async getMap(row) {
        const code = {
          csmCode: row.csmCode
        }
        const res = await customerLocation(code)
        this.$refs.customerLocation.open(res)
      },
      batchAudit() {},
      exportFile(type) {
        const query = {
          ...this._getQuery(this.query),
          desensitizeFlag: type
        }
        query[this.qtype] = this.txt
        if (this.qtype === 'cardType1') {
          query.cardType = 1
          query.cardNo = this.txt
          delete query.cardType1
        } else if (this.qtype === 'cardType2') {
          query.cardType = 2
          query.cardNo = this.txt
          delete query.cardType2
        }
        if (this.qtype !== 'cardType1' && this.qtype !== 'cardType2') {
          if (query.cardNo) delete query.cardNo
        }
        if (this.date && this.date.length === 2) {
          // query[this.dateType] = moment(this.date[0]).format()
          // query[`${this.dateType}End`] = moment(this.date[1]).format()
          query[this.dateType] = this.date[0].toISOString()
          query[`${this.dateType}End`] = this.date[1].toISOString()
        }
        let csmQuality = this.query.unCheckQuality
        if (this.customerLerel === 1) {
          query.csmQuality = csmQuality
        } else {
          if (!csmQuality) {
            csmQuality = 0
          }
          query.unCheckQuality = csmQuality
        }
        if (!this.query.csmStatus) query.csmStatus = 9
        if (query.warnLevel === 0) query.warnLevel = -1
        var list = JSON.parse(JSON.stringify(this.column))
        list.pop()
        list.shift()
        const value = {}
        list.forEach(l => {
          value[l.prop] = l.label
          return value
        })
        this.$refs.export.open(query, value)
      },
      del(row, index) {
        const code = {
          csmId: row.csmId
        }
        this.$refs.xiaohu.open(code, row)
      },
      async xiaoHuFn(params) {
        const res = await customerCancle(params)
        if (!res.data) {
          this.$message.success('销户成功')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          this.$message({
            dangerouslyUseHTMLString: true,
            type: 'warning',
            message: res.data
          })
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 查看隐患等级
      warnInfo(row) {
        this.$refs.warnInfo.open(row)
      },
      // 查看详情
      async opencsmGroupDetaill(row) {
        await this.$refs.csmGroupDetail.open(row)
      },
      // 移除组
      removeGroup(row) {
        this.$confirm(`您确认移除组吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          const params = {
            csmId: row.csmId
          }
          cancelCsmGroup(params).then(res => {
            if (res.data) {
              this.$message.success('操作成功')
              this.upDataTable()
            }
          })
        })
      },
      async blacklistCsm(row) {
        await this.$refs.blacklistCsm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },

      updateCsmStatus(row) {
        if (row.csmStatus === 2) {
          this.$confirm(`确定将该用户拉黑？`, '提示', {
            type: 'warning'
          }).then(() => {
            const params = {
              csmId: row.csmId,
              csmStatus: 4
            }
            updateCsmStatus(params).then(res => {
              if (res.data) {
                this.$message.success('操作成功')
                this.upDataTable()
              }
            })
          })
        } else {
          const params = {
            csmId: row.csmId,
            csmStatus: 2
          }
          updateCsmStatus(params).then(res => {
            if (res.data) {
              this.$message.success('操作成功')
              this.upDataTable()
            }
          })
        }
      },
      async tryPrint(row) {
        const { status, data } = await csmCancelPrint({ csmId: row.csmId })
        if (status === 200) {
          this.print(row, data)
        }
      },
      print(row2, resdata) {
        const row = JSON.parse(JSON.stringify(row2))
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['31']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        if (row.cancelTime) {
          row.cancelDt = parseTime(row.cancelTime, '{y}-{m}-{d} {h}:{i}:{s}')
        } else {
          row.cancelDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
        }
        row.csmAddress = row.csmRgAddress.replace(
          /([\u4E00-\u9FA5]*)([省市])(\s*)([\u4E00-\u9FA5]*)市/g,
          ''
        )
        let printcmd = {
          cmd: 2,
          title: `正在对销户单${row.csmCode}进行配送单打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }
        if (!window.jCPrint || !window.jCPrint.ws) {
          this.$message.error('打印未连接')
          return
        }
        window.jCPrint.process(printcmd, temp, row, resdata)
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接')
        }
      },
      // 获取区
      async getAreaData() {
        const res = await selectAreaCode({ areaCode: this.userInfo.cityCode })
        this.areaData = res.data.map(item => {
          return {
            value: item.areaCode,
            desc: item.areaName
          }
        })
      },
      async getStreetlist() {
        this.query.streetCode = ''
        const res = await selectAreaCode({ areaCode: this.query.countryCode })
        this.streetlist = res.data.map(item => {
          return {
            value: item.areaCode,
            desc: item.areaName
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
